
#include "pbm.h"

#include "xapp_ota.h"
#include "xapp_system.h"

#include "em_ble.h"

#if 1 // DFU 
static pbd_err_code_t pf_dfu_encode(   xapp_ota_type_t type,
                            uint8_t *p_req, 
                            uint16_t len, 
                            uint8_t *p_res, 
                            uint16_t *p_size)
{
    xapp_ota_req_t req;
    req.type = type;
    req.has_crypto = 0;
    req.req.pdata = p_req;
    req.req.len = len;

    xapp_ota_resp_t resp;
    xapp_ota_req_handle( &req, &resp);

    pbd_err_code_t err_code = PBD_SUCCESS;
    if( resp.len == 0)
    {
        *p_size = 0; 
        return err_code;
    }
    
    
    switch( resp.type)
    {
        case XAPP_OTA_TYPE_NONE:
        break;
        case XAPP_OTA_TYPE_POS:
        memcpy( p_res, resp.data, resp.len);
        *p_size = resp.len;
        break;
        case XAPP_OTA_TYPE_NEGA:
        memcpy( p_res, resp.data, resp.len);
        *p_size = resp.len;
        err_code = PBD_ERR_UNKOWN; 
        break; 
    }
    return err_code; 
}

pbd_err_code_t pi_dfu_init(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    pbd_err_code_t ret = pf_dfu_encode( XAPP_OTA_TYPE_INIT, p_req, len, p_res, p_size);
    if( ret == PBD_SUCCESS )
    {
         xapp_system_set_mode( SYSTEM_MODE_DFU );
    }
    
    return ret;
}
pbd_err_code_t pi_dfu_write(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    return pf_dfu_encode( XAPP_OTA_TYPE_WRITE, p_req, len, p_res, p_size);
}
pbd_err_code_t pi_dfu_execute(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    return pf_dfu_encode( XAPP_OTA_TYPE_EXECUTE, p_req, len, p_res, p_size);
}
pbd_err_code_t pi_dfu_query(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    return pf_dfu_encode( XAPP_OTA_TYPE_QUERY, p_req, len, p_res, p_size);
}
pbd_err_code_t pi_dfu_reset(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    return pf_dfu_encode( XAPP_OTA_TYPE_RESET, p_req, len, p_res, p_size);
}
pbd_err_code_t pi_dfu_query_mtu(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    return pf_dfu_encode( XAPP_OTA_TYPE_MTU, p_req, len, p_res, p_size);
}
pbd_err_code_t pi_dfu_version_req(uint8_t *p_req, uint16_t len, uint8_t *p_res, uint16_t *p_size)
{
    return pf_dfu_encode( XAPP_OTA_TYPE_VERSION, p_req, len, p_res, p_size); 
}


void pi_dfu_dfu_init_ok(pb_tx_array_handle_t cb)
{
    uint8_t resp[3];
    resp[0] = PBD_COMMAND_DFU_INIT;
    resp[1] = 0;

    pb_assemble_tx_data( resp, 2, 0, cb); 
}
#endif // !DFU 
